"use client"

import { useState, useEffect, useCallback } from "react"
import {
  Table,
  Card,
  Button,
  Input,
  Space,
  Popconfirm,
  message,
  Tag,
  Modal,
  Form,
  Select,
  DatePicker,
  Row,
  Col,
  Typography,
} from "antd"
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  PhoneOutlined,
  MailOutlined,
} from "@ant-design/icons"
// 移除直接axios导入，改为导入api函数
import {
  getCustomers,
  addCustomer,
  updateCustomer,
  deleteCustomer,
} from "@/utils/api/customer"
import dayjs from "dayjs"

const { Title } = Typography
const { Option } = Select

const CustomerManagement = () => {
  const [loading, setLoading] = useState(false)
  const [customers, setCustomers] = useState([])
  const [modalVisible, setModalVisible] = useState(false)
  const [modalTitle, setModalTitle] = useState("添加客户")
  const [selectedCustomer, setSelectedCustomer] = useState(null)
  const [form] = Form.useForm()
  const [searchText, setSearchText] = useState("")

  // 获取客户列表 - 使用api函数
  const fetchCustomers = useCallback(async () => {
    try {
      setLoading(true)
      // 直接使用getCustomers()函数，request.js已处理了baseURL和response.data
      const data = await getCustomers()
      setCustomers(data)
    } catch (error) {
      console.error("获取客户列表错误:", error)
      message.error("获取客户列表失败")
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    fetchCustomers()
  }, [fetchCustomers])

  // 搜索过滤
  const filteredCustomers = customers.filter(
    (customer) =>
      customer.name.toLowerCase().includes(searchText.toLowerCase()) ||
      customer.phone.includes(searchText) ||
      customer.email.toLowerCase().includes(searchText.toLowerCase())
  )

  // 添加或更新客户 - 使用api函数
  const handleSaveCustomer = async () => {
    try {
      const values = await form.validateFields()

      if (selectedCustomer) {
        // 更新客户
        await updateCustomer(selectedCustomer.id, values)
        message.success("客户信息更新成功")
      } else {
        // 添加客户
        await addCustomer(values)
        message.success("客户添加成功")
      }

      setModalVisible(false)
      form.resetFields()
      fetchCustomers()
    } catch (error) {
      console.error("保存客户信息错误:", error)
      message.error("操作失败，请稍后重试")
    }
  }

  // 删除客户 - 使用api函数
  const handleDeleteCustomer = async (id) => {
    try {
      await deleteCustomer(id)
      message.success("客户删除成功")
      fetchCustomers()
    } catch (error) {
      console.error("删除客户错误:", error)
      message.error("删除客户失败，请稍后重试")
    }
  }

  // 打开编辑模态框
  const handleEditCustomer = (customer) => {
    setSelectedCustomer(customer)
    setModalTitle("编辑客户信息")
    form.setFieldsValue({
      ...customer,
      weddingDate: customer.weddingDate ? dayjs(customer.weddingDate) : null,
    })
    setModalVisible(true)
  }

  // 打开添加模态框
  const handleAddCustomer = () => {
    setSelectedCustomer(null)
    setModalTitle("添加客户")
    form.resetFields()
    setModalVisible(true)
  }

  const columns = [
    {
      title: "客户姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "手机号码",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "婚礼日期",
      dataIndex: "weddingDate",
      key: "weddingDate",
    },
    {
      title: "预算范围",
      dataIndex: "budget",
      key: "budget",
      render: (budget) => `${budget} 万元`,
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        let color = "default"
        let text = "未知"

        switch (status) {
          case "potential":
            color = "purple"
            text = "潜在客户"
            break
          case "confirmed":
            color = "green"
            text = "已确认"
            break
          case "completed":
            color = "blue"
            text = "已完成"
            break
          case "canceled":
            color = "red"
            text = "已取消"
            break
          default:
            color = "default"
            text = status
        }

        return <Tag color={color}>{text}</Tag>
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="small">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEditCustomer(record)}
          />
          <Popconfirm
            title="确定要删除此客户吗?"
            description="此操作不可撤销!"
            onConfirm={() => handleDeleteCustomer(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className="customer-management">
      <div className="page-header">
        <Title level={4} className="page-title">
          客户管理
        </Title>
      </div>

      <Card>
        <div className="table-operations">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAddCustomer}
          >
            添加客户
          </Button>
          <div className="table-search">
            <Input
              placeholder="搜索客户名称、电话或邮箱"
              prefix={<SearchOutlined />}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: 300 }}
              allowClear
            />
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={filteredCustomers}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title={modalTitle}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSaveCustomer}
        width={720}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="客户姓名"
                rules={[{ required: true, message: "请输入客户姓名" }]}
              >
                <Input prefix={<UserOutlined />} placeholder="请输入客户姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号码"
                rules={[
                  { required: true, message: "请输入手机号码" },
                  { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号码" },
                ]}
              >
                <Input
                  prefix={<PhoneOutlined />}
                  placeholder="请输入手机号码"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="电子邮箱"
                rules={[
                  { required: true, message: "请输入电子邮箱" },
                  { type: "email", message: "请输入有效的电子邮箱" },
                ]}
              >
                <Input prefix={<MailOutlined />} placeholder="请输入电子邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="客户状态"
                rules={[{ required: true, message: "请选择客户状态" }]}
              >
                <Select placeholder="请选择客户状态">
                  <Option value="potential">潜在客户</Option>
                  <Option value="confirmed">已确认</Option>
                  <Option value="completed">已完成</Option>
                  <Option value="canceled">已取消</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="weddingDate" label="婚礼日期">
                <DatePicker
                  style={{ width: "100%" }}
                  placeholder="请选择婚礼日期"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="budget" label="预算范围(万元)">
                <Select placeholder="请选择预算范围">
                  <Option value="10-20">10-20 万元</Option>
                  <Option value="20-50">20-50 万元</Option>
                  <Option value="50-100">50-100 万元</Option>
                  <Option value="100+">100+ 万元</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={4} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default CustomerManagement
